<template>
  <div
    :class="[className]"
    :style="[computedStyle]"
    class="template-main-wrapper">
    <elements />
    <delete-context-menu />
    <div
      :style="[computedInnerStyle]"
      class="compont"
      id="previewCompont"
      ref="capture"></div>
  </div>
</template>

<script>
import html2canvas from 'html2canvas'
import $ from 'jquery'
import DeleteContextMenu from './TemplateComponents/DeleteContextMenu'
import Elements from './TemplateComponents/Elements'
import { TemplateOptions } from '@/mixins/previewTemplate.js'
export default {
  name: 'template-main',
  mixins: [TemplateOptions],
  components: {
    /* eslint-disable vue/no-unused-components */
    DeleteContextMenu,
    Elements
  },
  props: {
    className: {
      type: String,
      default: ''
    },
    wrapperSize: {
      type: [String, Number],
      default: 580
    },
    templateOpts: { // 模板数据设置, 请一定设置width与height 比例将由此计算
      type: Object,
      default() {
        return {
          width: 4000, // 默认宽高是4000
          height: 4000
        }
      }
    },
    twidget: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      widgetData: {},
      iwidthPercent: 0,
      iheightPercent: 0
    }
  },
  computed: {
    computedStyle() {
      let w = this.wrapperSize
      let h = this.wrapperSize
      if (typeof w === 'number') {
        w = isNaN(w) ? '' : `${w}px`
      }
      if (typeof h === 'number') {
        h = isNaN(h) ? '' : `${h}px`
      }
      let styles = {}
      if (w) styles.width = w
      if (h) styles.height = h

      return styles
    },
    computedInnerStyle() {
      const {width, height} = this.templateOpts // 现实模版宽高
      let {width: wrapWidth, height: wrapHeight} = this.computedStyle // 容器宽高
      wrapWidth = Number(wrapWidth.replace('px', ''))
      wrapHeight = Number(wrapHeight.replace('px', ''))

      let styleWidth; // 最终模版在容器的宽
      let styleHeight; // 最终模版在容器的高
      let ratio; // 缩放比
      
      let wrapRatio = width / height
      if(wrapRatio > 1) {
        ratio = wrapWidth / width
        styleWidth = `${wrapWidth}px`
        styleHeight = `${height * ratio}px`
      }else if(wrapRatio < 1) {
        ratio = wrapHeight / height
        styleWidth = `${width * ratio}px`
        styleHeight = `${wrapHeight}px`
      } else {
        ratio = wrapWidth / width
        styleWidth = `${wrapWidth}px`
        styleHeight = `${wrapHeight}px`
      }
      this.$nextTick(() => {
        this.iwidthPercent = ratio
        this.iheightPercent = ratio
        // 舞台已初始化好
        // 开始塞入组件
        this.layoutInit()
      })

      return {
        width: styleWidth,
        height: styleHeight
      }

    }
  }
}
</script>

<style lang="scss" scoped>
// import '@/styles/bs-common.scss';
.template-main-wrapper {
  border: 1px solid $bg-e9;
  position: relative;

  .compont {
    background: $bg-f4;
  }
}
</style>